package org.teamforce.demo2;

import java.lang.ref.WeakReference;

import org.teamforce.demo2.Constants.DlgType;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.AsyncTask;
import android.util.Log;

public class AsynchWorker extends AsyncTask<String, Integer, Integer> implements
		OnCancelListener {
	private WeakReference<Context> parentContext;
	private ProgressDialog pd;
	private DlgType dlgType;
	private final Integer numberOfSteps = 300;
	private final Integer delay = 100;

	AsynchWorker(final DlgType type, final Context context) {
		dlgType = type;
		parentContext = new WeakReference<Context>(context);
	}

	@Override
	protected final void onPreExecute() {
		switch (dlgType) {

		case activityIndicator:
			pd = ProgressDialog.show(parentContext.get(), "Go...",
					"In Progress...", true);
			break;
		case progressIndicator:
			pd = new ProgressDialog(parentContext.get());
			pd.setTitle("Go...");
			pd.setCancelable(true);
			pd.setOnCancelListener(this);
			pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			pd.setMax(numberOfSteps);
			pd.show();
			break;
		default:
			Log.d("AsynchWorker", "it is an error bud");
			break;
		}
		
	}

	@Override
	protected final void onProgressUpdate(final Integer... progress) {
		pd.setProgress(progress[0]);
	}

	@Override
	protected final void onPostExecute(final Integer result) {
		pd.dismiss();
		
	}

	protected final Integer doInBackground(final String... strings) {

		for (int i = 0; i < numberOfSteps; i++) {
			try {
				Thread.sleep(delay);
				publishProgress(i + 1);

			} catch (InterruptedException e) {
				Log.d("AsynchWorker", String.format(
						"Crazy world, I just done %1 steps!",
						Integer.valueOf(i + 1)));
			}

		}

		return 1;
	}

	@Override
	public final void onCancel(final DialogInterface dialog) {
		pd.dismiss();
		this.cancel(true);

	}
}
